package com.file.system.controller.system;


import cn.hutool.core.util.StrUtil;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.system.WebFileSystem;
import com.file.system.plugin.file.FileTool;
import com.file.system.service.system.IWebFileSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.file.system.tools.Formater.isLinux;


/**
 * 文件存储配置
 *
 * @author jch
 */
@RestController
@Validated
@RequestMapping("/web/file/system")
public class WebFileSystemController {

    @Autowired
    private IWebFileSystemService service;
    @Autowired
    private FileTool fileTool;


    /**
     * 查询文件存储配置
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/get")
    public CommonResult<WebFileSystem> getById() {
        WebFileSystem webFileSystem = service.getById(FileTool.sysFileId);
        return CommonResult.ok().setResult(webFileSystem);
    }

    /**
     * 编辑文件存储配置
     *
     * @param webFileSystem 文件存储配置
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/updateById")
    public CommonResult<WebFileSystem> in(@RequestBody @Validated(WebFileSystem.update.class) WebFileSystem webFileSystem) {
        if (StrUtil.isNotEmpty(webFileSystem.getRootPath())) {
            //判断根文件夹是否以 / 结尾
            if (webFileSystem.getRootPath().endsWith("/")) {
                webFileSystem.setRootPath(webFileSystem.getRootPath().substring(0, webFileSystem.getRootPath().length() - 1));
            }
            //linux 系统已 / 开始
            if (isLinux() && !webFileSystem.getRootPath().startsWith("/")) {
                webFileSystem.setRootPath("/" + webFileSystem.getRootPath());
            }
        }
        //编辑
        boolean state = service.updateById(webFileSystem);
        //修改系统缓存
        if (!state) {
            fileTool.init();
        }
        return CommonResult.check(state).setResult(webFileSystem);
    }

}

